package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.apache.commons.math3.analysis.function.Add;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备管理Service业务层处理
 * 
 * @author ych
 * @date 2025-10-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    @Override
    @Async
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);


        //从IOT中查询所有的数据
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("产品同步失败");


        }
        List<ProductSummary> products = response.getProducts();
        //放入到Redis中
        redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        // 从Redis中查询所有的产品
        String jesonStr = redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).get();
        return JSONUtil.toList(jesonStr, ProductVo.class);
    }

    @Override
    public void register(DeviceDto dto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getDeviceName, dto.getDeviceName());
        Device one = this.getOne(queryWrapper1);
        if (one != null) {
            throw new BaseException("设备名不能重复");
        }
        LambdaQueryWrapper<Device> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Device::getNodeId, dto.getNodeId());
        one = this.getOne(queryWrapper2);
        if (one != null) {
            throw new BaseException("设备标识不能重复");
        }
        LambdaQueryWrapper<Device> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(Device::getRemark, dto.getRemark());
        queryWrapper3.eq(Device::getProductKey, dto.getProductKey());
        one = this.getOne(queryWrapper3);
        if (one != null) {
            throw new BaseException("同一个位置不能有同一个设备");
        }
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();

        // addDevice.setDeviceId();
        addDevice.setNodeId(dto.getNodeId());
        addDevice.setDeviceName(dto.getDeviceName());
        addDevice.setProductId(dto.getProductKey());
        addDevice.setDescription(dto.getDeviceDescription());
        AuthInfo authInfo = new AuthInfo();
        String secret = RandomUtil.randomString(32);
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);

//        addDevice.setGatewayId();
//        addDevice.setAppId();
//        addDevice.setExtensionInfo();
//        addDevice.setShadow();
        request.setBody(addDevice);
        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("IOT注册失败");
        }
        String deviceId = response.getDeviceId();
        // 再保存自己的数据
        Device device = new Device();

        device.setIotId(deviceId);
        device.setSecret(secret);
        device.setBindingLocation(dto.getBindingLocation() + "");
        device.setLocationType(dto.getLocationType());
        device.setPhysicalLocationType(dto.getPhysicalLocationType());
        device.setDeviceName(dto.getDeviceName());
        device.setProductKey(dto.getProductKey());
        device.setProductName(dto.getProductName());
        device.setDeviceDescription(dto.getDeviceDescription());
        //device.setHaveEntranceGuard();
        device.setNodeId(dto.getNodeId());
        device.setRemark(dto.getRemark());
        this.save(device);

    }

    @Override
    public DeviceDetailVo deviceDetail(String iotId) {
        //1.先查询自己的表
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device one = this.getOne(queryWrapper);
        if (one == null) {
            throw new BaseException("参数有误");
        }
        DeviceDetailVo detailVo = BeanUtil.toBean(one, DeviceDetailVo.class);
        //2.再查询IOT
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("IOT查询失败");
        }
        String activeTimeStr = response.getActiveTime();
        LocalDateTime parse = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
        // DateTimeZoneConverter是今天资料中提供的一个工具类
        LocalDateTime activeTime = DateTimeZoneConverter.utcToShanghai(parse);
        detailVo.setActiveTime(activeTime);
        detailVo.setDeviceStatus(response.getStatus());
        return detailVo;
    }

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("IOT查询失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        DeviceShadowData deviceShadowData = shadow.get(0);
        DeviceShadowProperties reported = deviceShadowData.getReported();

        String eventTimeStr = reported.getEventTime();
        LocalDateTime parse = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // DateTimeZoneConverter是今天资料中提供的一个工具类
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(parse);

        ArrayList<DeviceDataVo> list = new ArrayList<DeviceDataVo>();
        LinkedHashMap<String, Object> linkedHashMap = (LinkedHashMap) reported.getProperties();
        for (String key : linkedHashMap.keySet()) {
            DeviceDataVo deviceDataVo = new DeviceDataVo();
            deviceDataVo.setFunctionId(key);
            deviceDataVo.setEventTime(eventTime);
            deviceDataVo.setValue(linkedHashMap.get(key));
            list.add(deviceDataVo);

        }
        return list;
    }

    @Override


    public void editDeviceInfo(DeviceDto dto) {
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getDeviceName,dto.getDeviceName());
        Device one = this.getOne(queryWrapper1);
        if (one!=null){
            throw new BaseException("设备名不能重复");
        }


//        LambdaQueryWrapper<Device> queryWrapper3 = new LambdaQueryWrapper<>();
//        queryWrapper3.eq(Device::getRemark,dto.getRemark());
//        queryWrapper3.eq(Device::getProductKey,dto.getProductKey());
//        one = this.getOne(queryWrapper3);

        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(dto.iotId);
        UpdateDevice body = new UpdateDevice();

        body.setDeviceName(dto.getDeviceName());

        body.setDescription(dto.getDeviceDescription());

        request.setBody(body);

        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode()!=200){
            throw new BaseException("IOT修改失败");
        }
        //修改本地
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId,dto.iotId);
        one = this.getOne(queryWrapper);
        if (one == null){
            throw  new BaseException("设备不存在");
        }
        one.setDeviceName(dto.getDeviceName());
        one.setBindingLocation(String.valueOf(dto.getBindingLocation()));
        one.setLocationType(dto.getLocationType());
        one.setNodeId(dto.getNodeId());
        one.setPhysicalLocationType(dto.getPhysicalLocationType());
        one.setProductKey(dto.productKey);
        one.setRemark(dto.getRemark());
        one.setDeviceDescription(dto.getDeviceDescription());
        this.updateById(one);
    }

    @Override
    public void deleteDevice(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();

        request.setDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode() != 204) {
            throw new BaseException("IOT删除失败");
        }
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
       Device one = this.getOne(queryWrapper);
        if (one == null) {
            throw new BaseException("设备不存在");
        }
      this.removeById(one);
    }

    @Override
    public AjaxResult queryProductById(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("IOT产品查询失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        return AjaxResult.success(serviceCapabilities);
    }


}


